package com.zyf.project.capchain.utils.cryptology;

import com.zyf.project.capchain.utils.exceptions.CryptologicalException;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * @author Zhou Yifan
 */
public class Coder {

    public static final String KEY_SHA = "SHA";
    public static final String KEY_MD5 = "MD5";

    private Coder() {
    }

    /**
     * MAC算法可选以下多种算法
     *
     * <pre>
     * HmacMD5
     * HmacSHA256
     * </pre>
     */
    public static final String KEY_MAC = "HmacMD5";

    /**
     * BASE64解码
     *
     * @param key 待解码字符串
     * @return 解码后的字符串
     * @throws CryptologicalException 可能出现的异常
     */
    public static byte[] decryptBase64(String key) {
        Base64.Decoder decoder = Base64.getDecoder();
        return decoder.decode(key);
    }

    /**
     * BASE64编码
     *
     * @param key 待编码字符串
     * @return 编码后的字符串
     * @throws CryptologicalException 可能出现的异常
     */
    public static String encryptBase64(byte[] key) {
        Base64.Encoder encoder = Base64.getEncoder();
        return encoder.encodeToString(key);
    }

    /**
     * MD5加密
     *
     * @param data 待加密数据
     * @return 加密后的数据
     * @throws CryptologicalException 可能出现的异常
     */
    public static byte[] encryptMd5(byte[] data) throws NoSuchAlgorithmException {

        MessageDigest md5 = MessageDigest.getInstance(KEY_MD5);
        md5.update(data);

        return md5.digest();

    }

    /**
     * SHA加密
     *
     * @param data 待加密数据
     * @return 加密后的数据
     * @throws NoSuchAlgorithmException 可能出现的异常
     */
    public static byte[] encryptSha(byte[] data) throws NoSuchAlgorithmException {

        MessageDigest sha = MessageDigest.getInstance(KEY_SHA);
        sha.update(data);

        return sha.digest();

    }

    /**
     * 初始化HMAC密钥
     *
     * @return 加密后的数据
     * @throws CryptologicalException 可能出现的异常
     */
    public static String initMacKey() throws CryptologicalException, NoSuchAlgorithmException {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_MAC);

        SecretKey secretKey = keyGenerator.generateKey();
        return encryptBase64(secretKey.getEncoded());
    }

    /**
     * HMAC加密
     *
     * @param data 待加密数据
     * @param key 加密方式
     * @return 加密后的数据
     * @throws CryptologicalException 可能出现的异常
     */
    public static byte[] encryptHmac(byte[] data, String key) throws CryptologicalException, NoSuchAlgorithmException, InvalidKeyException {

        SecretKey secretKey = new SecretKeySpec(decryptBase64(key), KEY_MAC);
        Mac mac = Mac.getInstance(secretKey.getAlgorithm());
        mac.init(secretKey);

        return mac.doFinal(data);

    }

}
